package com.csthink.web.application.service.impl;

import com.csthink.common.infrastructure.util.IDGenerator;
import com.csthink.mysql.entity.Account;
import com.csthink.mysql.entity.User;
import com.csthink.mysql.repository.AccountRepository;
import com.csthink.web.application.dto.test.AccountSetupRequest;
import com.csthink.web.application.service.AccountService;
import com.csthink.web.application.service.UserService;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-10
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Setter(onMethod_ = @Autowired)
    private AccountRepository accountRepository;

    @Setter(onMethod_ = @Autowired)
    private UserService userService;

    @Override
    public Account getAccount(User loginUser) {
        String accountId = loginUser.getAccountId();
        return accountRepository.getById(accountId);
    }

    @Override
    public Boolean saveAccount(Account account) {
        if (Objects.isNull(account)) {
            return false;
        }

        return accountRepository.save(account);
    }

    @Override
    public User initAccount(AccountSetupRequest request) {
        // todo check first

        Account account = new Account();
        String accountId = IDGenerator.getId();
        account.setId(accountId);
        account.setName(request.getAccountName());
        account.setEmail(request.getUserEmail());
        account.setIsSetup(1);
        account.setCreateBy("system");
        accountRepository.save(account);

        User user = new User();
        user.setAccountId(accountId);
        user.setEmail(request.getUserEmail());
        user.setCreateBy("system");

        return userService.saveUser(user);
    }

    @Override
    public Account getAccountByUsername(String username) {
        return null;
    }
}
